<template>
  <div class="notice-test-page">
    <a-card title="通知系统测试页面" class="test-card">
      <a-space direction="vertical" size="large" style="width: 100%;">
        
        <!-- 发送测试通知 -->
        <a-card title="发送测试通知" size="small">
          <a-form :model="testForm" layout="vertical">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="用户ID">
                  <a-input-number 
                    v-model="testForm.userId" 
                    placeholder="输入用户ID" 
                    style="width: 100%;"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="消息类型">
                  <a-select v-model="testForm.messageType" placeholder="选择消息类型">
                    <a-option :value="0">普通消息</a-option>
                    <a-option :value="1">紧急消息</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            
            <a-form-item label="消息标题">
              <a-input v-model="testForm.messageTitle" placeholder="输入消息标题" />
            </a-form-item>
            
            <a-form-item label="消息内容">
              <a-textarea 
                v-model="testForm.messageContent" 
                placeholder="输入消息内容"
                :rows="3"
              />
            </a-form-item>
            
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="sendTestNotice" :loading="sending">
                  发送通知
                </a-button>
                <a-button @click="resetForm">重置</a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 快速测试按钮 -->
        <a-card title="快速测试" size="small">
          <a-space wrap>
            <a-button type="outline" @click="sendQuickTest('普通消息')">
              发送普通消息
            </a-button>
            <a-button type="outline" status="warning" @click="sendQuickTest('紧急消息')">
              发送紧急消息
            </a-button>
            <a-button type="outline" @click="testSendToCurrentUser">
              发送给当前用户
            </a-button>
          </a-space>
        </a-card>

        <!-- 统计信息 -->
        <a-card title="消息统计" size="small">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-statistic title="未读消息" :value="stats.unreadCount" />
            </a-col>
            <a-col :span="8">
              <a-statistic title="总消息数" :value="stats.totalCount" />
            </a-col>
            <a-col :span="8">
              <a-statistic title="已读消息" :value="stats.readCount" />
            </a-col>
          </a-row>
          <a-button type="outline" @click="refreshStats" style="margin-top: 16px;">
            刷新统计
          </a-button>
        </a-card>

        <!-- WebSocket状态 -->
        <a-card title="WebSocket状态" size="small">
          <a-descriptions :column="2">
            <a-descriptions-item label="连接状态">
              <a-tag :color="wsStatus.connected ? 'green' : 'red'">
                {{ wsStatus.connected ? '已连接' : '未连接' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="重连次数">
              {{ wsStatus.retryCount }}
            </a-descriptions-item>
            <a-descriptions-item label="接收消息数">
              {{ wsStatus.messageCount }}
            </a-descriptions-item>
            <a-descriptions-item label="最后消息时间">
              {{ wsStatus.lastMessageTime || '无' }}
            </a-descriptions-item>
          </a-descriptions>
          <a-space style="margin-top: 16px;">
            <a-button type="outline" @click="reconnectWebSocket">
              重新连接
            </a-button>
            <a-button type="outline" @click="clearMessageLog">
              清空日志
            </a-button>
          </a-space>
        </a-card>

        <!-- 消息日志 -->
        <a-card title="消息接收日志" size="small">
          <div class="message-log">
            <div 
              v-for="(log, index) in messageLogs" 
              :key="index"
              class="log-item"
            >
              <span class="log-time">{{ log.time }}</span>
              <span class="log-type" :class="log.type">{{ log.type }}</span>
              <span class="log-content">{{ log.content }}</span>
            </div>
            <a-empty v-if="!messageLogs.length" description="暂无日志" />
          </div>
        </a-card>

      </a-space>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { 
  sendNoticeMessageApi, 
  testSendNoticeApi,
  getNoticeMessageStatsApi,
  getUnreadCountApi
} from '@/api/notice'
import useUserStore from '@/sotre/user-store'
import SocketService from '@/utils/web-stocket-service'

const userStore = useUserStore()

const sending = ref(false)
const testForm = reactive({
  userId: null,
  messageType: 0,
  messageTitle: '测试通知标题',
  messageContent: '这是一条测试通知消息内容'
})

const stats = reactive({
  unreadCount: 0,
  totalCount: 0,
  readCount: 0
})

const wsStatus = reactive({
  connected: false,
  retryCount: 0,
  messageCount: 0,
  lastMessageTime: null
})

const messageLogs = ref([])

// 发送测试通知
const sendTestNotice = async () => {
  if (!testForm.userId) {
    Message.warning('请输入用户ID')
    return
  }
  
  if (!testForm.messageTitle || !testForm.messageContent) {
    Message.warning('请输入消息标题和内容')
    return
  }
  
  try {
    sending.value = true
    const message = {
      userId: testForm.userId,
      messageType: testForm.messageType,
      messageTitle: testForm.messageTitle,
      messageContent: testForm.messageContent,
      read: false,
      status: false
    }
    
    const response = await sendNoticeMessageApi(message)
    if (response.data.code === '00000') {
      Message.success('发送成功')
      addLog('SEND', `发送通知给用户${testForm.userId}: ${testForm.messageTitle}`)
      refreshStats()
    } else {
      Message.error(response.data.msg || '发送失败')
    }
  } catch (error) {
    console.error('发送通知失败:', error)
    Message.error('发送失败')
  } finally {
    sending.value = false
  }
}

// 快速测试
const sendQuickTest = async (type) => {
  const messageType = type === '紧急消息' ? 1 : 0
  testForm.messageType = messageType
  testForm.messageTitle = `快速测试 - ${type}`
  testForm.messageContent = `这是一条${type}的快速测试内容，发送时间：${new Date().toLocaleString()}`
  
  if (!testForm.userId) {
    testForm.userId = userStore.userInfo?.id || 1
  }
  
  await sendTestNotice()
}

// 发送给当前用户
const testSendToCurrentUser = async () => {
  const currentUserId = userStore.userInfo?.id
  if (!currentUserId) {
    Message.warning('请先登录')
    return
  }
  
  try {
    const response = await testSendNoticeApi(currentUserId)
    if (response.data.code === '00000') {
      Message.success('发送成功，请查看通知')
      addLog('TEST', `发送测试通知给当前用户${currentUserId}`)
      refreshStats()
    } else {
      Message.error(response.data.msg || '发送失败')
    }
  } catch (error) {
    console.error('发送测试通知失败:', error)
    Message.error('发送失败')
  }
}

// 重置表单
const resetForm = () => {
  testForm.userId = null
  testForm.messageType = 0
  testForm.messageTitle = '测试通知标题'
  testForm.messageContent = '这是一条测试通知消息内容'
}

// 刷新统计
const refreshStats = async () => {
  try {
    const [statsResponse, countResponse] = await Promise.all([
      getNoticeMessageStatsApi(),
      getUnreadCountApi()
    ])
    
    if (statsResponse.data.code === '00000') {
      const data = statsResponse.data.data
      stats.totalCount = data.totalCount || 0
      stats.readCount = data.readCount || 0
    }
    
    if (countResponse.data.code === '00000') {
      stats.unreadCount = countResponse.data.data || 0
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 重新连接WebSocket
const reconnectWebSocket = () => {
  try {
    const socketService = SocketService.Instance
    socketService.connect()
    addLog('SYSTEM', 'WebSocket重新连接')
  } catch (error) {
    console.error('WebSocket重连失败:', error)
    addLog('ERROR', 'WebSocket重连失败')
  }
}

// 清空消息日志
const clearMessageLog = () => {
  messageLogs.value = []
  wsStatus.messageCount = 0
}

// 添加日志
const addLog = (type, content) => {
  const log = {
    time: new Date().toLocaleTimeString(),
    type: type,
    content: content
  }
  messageLogs.value.unshift(log)
  
  // 只保留最近100条日志
  if (messageLogs.value.length > 100) {
    messageLogs.value = messageLogs.value.slice(0, 100)
  }
}

// 监听WebSocket状态
const checkWebSocketStatus = () => {
  const socketService = SocketService.Instance
  if (socketService && socketService.ws) {
    wsStatus.connected = socketService.connected
    wsStatus.retryCount = socketService.connectRetryCount
  }
}

onMounted(() => {
  // 获取初始统计
  refreshStats()
  
  // 设置当前用户ID为默认值
  if (userStore.userInfo?.id) {
    testForm.userId = userStore.userInfo.id
  }
  
  // 检查WebSocket状态
  checkWebSocketStatus()
  
  // 定时检查WebSocket状态
  const statusTimer = setInterval(checkWebSocketStatus, 1000)
  
  // Hook into WebSocket message handler
  const socketService = SocketService.Instance
  if (socketService) {
    const originalMessage = socketService.message
    socketService.message = function(recvData) {
      // 调用原始处理
      originalMessage.call(this, recvData)
      
      // 记录日志
      wsStatus.messageCount++
      wsStatus.lastMessageTime = new Date().toLocaleTimeString()
      addLog('RECEIVE', `收到${recvData.code}消息: ${recvData.info?.title || recvData.info?.introduce || ''}`)
      
      // 更新统计
      if (recvData.code === 'NOTICE_MESSAGE') {
        setTimeout(refreshStats, 500)
      }
    }
  }
  
  onUnmounted(() => {
    clearInterval(statusTimer)
  })
})
</script>

<style scoped>
.notice-test-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.message-log {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid var(--color-border-2);
  border-radius: 6px;
  padding: 12px;
  background-color: var(--color-fill-1);
}

.log-item {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
}

.log-time {
  color: var(--color-text-3);
  min-width: 80px;
}

.log-type {
  min-width: 60px;
  font-weight: bold;
}

.log-type.SEND {
  color: #00b42a;
}

.log-type.RECEIVE {
  color: #165dff;
}

.log-type.TEST {
  color: #ff7d00;
}

.log-type.SYSTEM {
  color: #14c9c9;
}

.log-type.ERROR {
  color: #f53f3f;
}

.log-content {
  flex: 1;
  color: var(--color-text-2);
}
</style>